package org.example.design.prototype;

import org.example.util.Function;

import java.io.*;

/**
 * @author huangshen
 * @version 0
 * @description DeepClone
 * @since 2022/1/29 22:34
 */
public class DeepClone {
    public static Object deepClone(Object obj) {
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        try(
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);

        ) {
            oos.writeObject(obj);

            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);

            return ois.readObject();
        } catch (IOException | ClassNotFoundException exception) {
            System.out.println(exception.getMessage());
            return null;
        } finally {
            try {
                if (Function.equalsNull(bis)) {
                    bis.close();
                }
                if (Function.equalsNull(ois)) {
                    ois.close();
                }
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }
}
